<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\model\ding;

use app\api\service\User as UserService;
use app\common\model\ding\ShopApply as ShopApplyModel;
use cores\exception\BaseException;

use think\facade\Db;
/**
 * 商家申请
 * Class UserAddress
 * @package app\common\model
 */
class ShopApply extends ShopApplyModel {
	/**
	 * 隐藏字段
	 * @var array
	 */
	protected $hidden = [
		'is_delete',
		'store_id',
		'create_time',
		'update_time',
	];

//    /**
	//     * 地区名称
	//     * @param $value
	//     * @param $data
	//     * @return array
	//     */
	//    public function getRegionAttr($value, $data)
	//    {
	//        return array_values(parent::getRegionAttr($value, $data));
	//    }

	/**
	 * 新增收货地址
	 * @param array $data
	 * @return mixed
	 * @throws BaseException
	 */
	public function add(array $data) {
		// 当前用户ID
		$userId = UserService::getCurrentLoginUserId();
		// 省市区ID
		[$data['province_id'], $data['city_id'], $data['region_id']] = $this->getRegionId($data);

		//推荐关系
		$refeer = Db::name('dealer_referee')->where('user_id', $userId)->find();
		if ($refeer) {
			$data['daili_user_id'] = $refeer['dealer_id'];
		} else {
			$data['daili_user_id'] = 0;
		}

		return $this->transaction(function () use ($data) {
			$this->save([
				'shop_name' => $data['shop_name'],
				'real_name' => $data['real_name'],
				'mobile' => $data['mobile'],
				'province_id' => $data['province_id'],
				'city_id' => $data['city_id'],
				'region_id' => $data['region_id'],
				'address' => $data['address'],
				'daili_user_id' => $data['daili_user_id'],

				'store_id' => self::$storeId,
			]);

			return true;
		});
	}

	/**
	 * 格式化用户上传的省市区数据
	 * @param array $data
	 * @return array
	 * @throws BaseException
	 */
	private function getRegionId(array $data) {
		if (!isset($data['region'])) {
			throwError('省市区不能为空');
		}
		if (count($data['region']) != 3) {
			throwError('省市区数据不合法');
		}
		return array_map(function ($item) {
			return $item['value'];
		}, $data['region']);
	}

}
